import axios from "axios";
import cookie from "./cookie.js";
import router from "../../router";
import qs from 'qs';
import store from '../../store';
import swal from 'sweetalert'

axios.defaults.timeout = 10000;

axios.interceptors.request.use(function(config) { // 请求之前做一些拦截处理
  config.headers.userId = cookie.getCookie("userId");
  config.headers.account = cookie.getCookie("account");
  config.headers.ticket = cookie.getCookie("ticket");
  config.headers.platform = 'PC';
  config.headers.lang = 'zh';//中文zh 英文en 日文jp
  store.dispatch('loginChange', cookie.getCookie("ticket"))
  if (config.method == 'post') {
    config.data = qs.stringify(config.data);
  }
  return config;
});

axios.interceptors.response.use((data) => {
  store.dispatch('ifLoadingChange', false);
  // console.log(router.history.current.path)
  let path = router.history.current.path;
  if (data.data.code == "002" && path == '/trade') {
    store.dispatch('loginChange', false)
  }

  if (data.data.code == "002" && path != '/trade') { //用户未登录
    store.dispatch('loginChange', false)
    swal('请先登录再进行操作',{
      icon:'/static/img/tan_chuang.png'
    }).then(()=>{
      router.push({
        path:"/login",
        query:{redirect:encodeURIComponent(window.location.href)}
      });
    })
    
  } else {
    return data;
  }
}, (err) => {
  store.dispatch('ifLoadingChange', false)
});

export default axios;
